<template>
  <div class='CheckBusinessConfigDetailClass'>
    <div class="flex-end">
      <el-button @click="handleAdd('module')"
                 v-if="pageType===2"
                 type="primary">添加模块
      </el-button>
      <el-button @click="handleAdd('process')"
                 v-if="(pageType===3 || pageType===4)"
                 type="primary">添加过程
      </el-button>
      <el-button type="primary"
                 @click="_multipleDelete">批量删除</el-button>
    </div>

    <el-form ref="ruleForm"
             :model="configTableData">
      <el-table :data="configTableData.list"
                :key="1"
                height="600px"
                class="check-item-list"
                @selection-change="handleSelectionChange"
                :header-cell-style="{background:'#f5f5f5'}">
        <el-table-column :selectable="isDisabled"
                         type="selection"
                         width="55">
        </el-table-column>
        <el-table-column type="index"
                         label="序号">
        </el-table-column>
        <el-table-column label="节点"
                         width="100"
                         v-if="(pageType===3 || pageType===4)">
          <template slot-scope="scope">
            <p v-if="scope.$index===0">开始</p>
            <p v-else-if="scope.$index===configTableData.list.length-1">结束</p>
            <p v-else>过程{{scope.$index}}</p>
          </template>
        </el-table-column>

        <el-table-column label="模块名称"
                         key="name">
          <template slot-scope="scope">
            <el-form-item>
              <el-input v-model="scope.row.module_name"
                        clearable></el-input>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="状态名"
                         key="status"
                         v-if="(pageType===3 || pageType===4)">
          <template slot-scope="scope">
            <el-form-item>
              <el-input v-model="scope.row.status_name"
                        clearable></el-input>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="关联表单"
                         key="form">
          <template slot-scope="scope">
            <el-form-item :prop="'list.' + scope.$index + '.check_item_id'"
                          :rules="((pageType===3 || pageType===4)&&scope.$index===configTableData.list.length-1)?
                          undefined:[{ required: true, message: '请输入'}]">
              <el-select v-model="scope.row.check_item_id"
                         filterable
                         clearable
                         @change="_changeLinkFormList(scope.row,scope.$index)"
                         :disabled="(pageType===3 || pageType===4)&&scope.$index===configTableData.list.length-1">
                <el-option v-for="item in link_form_list"
                           :key="item.check_item_id"
                           :label="item.check_item_name"
                           :value="item.check_item_id"></el-option>
              </el-select>
            </el-form-item>

          </template>
        </el-table-column>

        <!-- <el-table-column label="显示对象"
                         key="object">
          <template slot-scope="scope">
            <el-form-item :prop="'list.' + scope.$index + '.show_obj_name'"
                          :rules="((pageType===3 || pageType===4)&&scope.$index!==0)?
                          undefined:[{ required: true, message: '请输入'}]">
              <el-select v-model="scope.row.show_obj_name"
                         filterable
                         clearable
                         @focus="getShowObjList(scope.row.check_item_id,scope.$index)"
                         :disabled="(pageType===3 || pageType===4)&&scope.$index!==0">
                <el-option v-for="item in scope.row.show_obj_list"
                           :key="item.show_obj"
                           :label="item.show_obj_name"
                           :value="item.show_obj_name"></el-option>
              </el-select>

            </el-form-item>

          </template>
        </el-table-column> -->
        <el-table-column label="流程判断"
                         v-if=" pageType===4"
                         key="flow">
          <template slot-scope="scope">
            <el-button v-if="scope.row.check_item_id"
                       @click="configFlow(scope.row,scope.$index)"
                       type="text">配置</el-button>
          </template>
        </el-table-column>
        <el-table-column v-if="pageType===2"
                         key="is_edit"
                         label="提交后是否可编辑">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.is_edit"
                       active-value="1"
                       inactive-value="0">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text"
                       v-if="!((pageType===3 || pageType===4)&&scope.$index!==0)"
                       @click="moduleListConfig(scope.row)">列表设置</el-button>
            <el-button @click="deleteItem(scope.row,scope.$index)"
                       v-if="!((pageType===3 || pageType===4)&&(scope.$index===configTableData.list.length-1||scope.$index===0))"
                       type="text">删除
            </el-button>
          </template>

        </el-table-column>
      </el-table>

    </el-form>

    <div class="btn-groups">
      <el-button @click="_saveBusinessConfig"
                 type="primary">保存
      </el-button>
      <el-button @click="back">取消</el-button>
    </div>
    <!-- 流程判断弹框 -->
    <el-dialog title="流程判断配置"
               :visible.sync="configFlowDialogVisible">
      <div v-for="(flowItem,index) in configFlowDialogData"
           :key="index">
        <el-form :ref="'configFlowForm'+index"
                 class="flow-config-container"
                 :rules="configFlowRules"
                 :model="flowItem"
                 label-width="0px">
          <el-form-item prop="content_id">
            <el-select v-model="flowItem.content_id"
                       placeholder="">
              <el-option v-for="item in fieldList"
                         :key="item.show_obj"
                         :label="item.show_obj_name"
                         :value="item.show_obj">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="operator"
                        prop="operator">
            <el-input v-model="flowItem.operator"
                      disabled></el-input>
          </el-form-item>
          <el-form-item prop="value"
                        class="value">
            <el-input v-model="flowItem.value"></el-input>
          </el-form-item>
          <el-form-item prop="operation_type"
                        class="operation-type">
            <el-select v-model="flowItem.operation_type"
                       placeholder="">
              <el-option v-for="item in configFlowOperationTypeList"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="check_module_id"
                        v-if="flowItem.operation_type==='3' || flowItem.operation_type==='2'">
            <el-select v-model="flowItem.check_module_id"
                       placeholder="">
              <el-option v-for="item in flowList"
                         :key="item.node_no"
                         :label="item.module_name"
                         :value="item.check_module_id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button v-if="index===0"
                       @click="addFlowConfig"
                       type="text">添加</el-button>
            <el-button v-else
                       @click="deleteFlowConfig(index)"
                       type="text">删除</el-button>
          </el-form-item>
        </el-form>

      </div>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="configFlowDialogVisible=false">取 消</el-button>
        <el-button @click="configFlowConfirm"
                   type="primary">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 列表设置弹框 -->
    <ListConfigDialog @callback="editConfigCb"
                      :dialogVisible.sync="listConfigDialogVisible"
                      :dialogData="listConfigDialogData"></ListConfigDialog>
  </div>
</template>
<script>
import { CommonCheckApi } from '@/services/SystemSetting'
import ChooseCheckItemDialog from './components/ChooseCheckItemDialog'
import ListConfigDialog from '@/pages/ConfigCenter/CommonCheck/components/ListConfigDialog'
export default {
  data () {
    return {
      //（2：独立模式，3：流程模式）
      pageType: 3,
      // 获取已绑定检查项列表参数
      requestParam: {
        check_tpl_id: '',
        is_page: 0,
        page: 1,
        page_size: 10
      },
      link_form_list: [],
      show_obj_list: [],
      // 已绑定检查项列表
      configTableData: {
        list: []
      },
      multipleSelection: [],
      checkItemMap: new Map(),
      // 流程配置弹框是否可见
      configFlowDialogVisible: false,
      // 流程配置弹框数据
      configFlowDialogData: [],
      resetConfigFlowDialogData: {
        content_id: '',
        operator: '=',
        value: '',
        operation_type: '',
        check_module_id: ''
      },
      // 当前配置流程判断的行
      choosedRow: {},
      configFlowOperationTypeList: [
        { label: '仅保存数据', value: '1' },
        { label: '仅跳转流程', value: '2' },
        { label: '保存数据并跳转', value: '3' }
      ],
      configFlowRules: {
        content_id: [
          { required: true, message: '请选择字段', trigger: 'change' }
        ],
        value: [
          { required: true, message: '请输入值', trigger: 'blur' }
        ],
        operation_type: [
          { required: true, message: '请选择操作方式', trigger: 'change' }
        ],
        check_module_id: [
          { required: true, message: '请选择跳转流程', trigger: 'change' }
        ]
      },
      // 表单的字段列表
      fieldList: [],
      // 是否存在数据源表单
      hasDataSource: false,
      // 选择跳转流程时，下拉框中的流程列表
      flowList: [],
      // 列表配置弹框是否可见
      listConfigDialogVisible: false,
      // 列表配置弹框数据
      listConfigDialogData: {
        show_obj_list: [],
        show_cfg: {}
      },
      // 当前操作行
      currentRow: {}
    }
  },
  components: {
    ChooseCheckItemDialog,
    ListConfigDialog
  },
  methods: {
    // 列表属性配置回调
    editConfigCb (data) {
      this.currentRow.show_obj_list = data.show_obj_list
      this.currentRow.show_cfg = data.show_cfg
    },
    // 列表属性配置
    moduleListConfig (row) {
      this.currentRow = row
      this.listConfigDialogData = {
        show_obj_list: row.show_obj_list,
        show_cfg: row.show_cfg || {}
      }
      this.listConfigDialogVisible = true
    },
    // 流程判断确认
    configFlowConfirm () {
      let len = this.configFlowDialogData.length
      let flag = true
      for (let i = 0; i < len; i++) {
        let form = 'configFlowForm' + i

        this.$refs[form][0].validate((valid) => {
          if (!valid) flag = false
        })
      }
      if (flag) {
        this.choosedRow.flow_cfg = JSON.parse(JSON.stringify(this.configFlowDialogData))
        this.configFlowDialogVisible = false
      }
      // this.$refs.configFlowForm.validate((valid) => {
      //   if (valid) {
      //     this.choosedRow.flow_cfg = JSON.parse(JSON.stringify(this.configFlowDialogData))
      //     this.configFlowDialogVisible = false
      //   }
      // })      
    },
    // 添加流程判断
    addFlowConfig () {
      let reset = JSON.parse(JSON.stringify(this.resetConfigFlowDialogData))
      this.configFlowDialogData.push(reset)
    },
    // 删除流程判断
    deleteFlowConfig (index) {
      this.configFlowDialogData.splice(index, 1)
    },
    // 流程判断配置
    configFlow (row, index) {
      // this.$set(this.configTableData.list[index], 'flow_cfg', {})
      let reset = JSON.parse(JSON.stringify(this.resetConfigFlowDialogData))
      row.flow_cfg = row.flow_cfg || []
      if (row.flow_cfg.length > 0) {
        this.configFlowDialogData = JSON.parse(JSON.stringify(row.flow_cfg))
      } else {
        this.configFlowDialogData = [reset]
      }

      this.choosedRow = this.configTableData.list[index]
      this.choosedRow.flow_cfg = this.configFlowDialogData
      this.configFlowDialogVisible = true
      // 根据表单获取字段列表
      CommonCheckApi.getShowObjListAPI({
        params: { check_item_id: row.check_item_id }
      }).then(res => {
        this.fieldList = res.data.list
      })
      // 过滤掉当前选中数据及新添加的数据
      this.flowList = this.configTableData.list.filter((item) => {
        return item.check_module_id && item.check_module_id != row.check_module_id
      })
    },
    back () {
      this.$router.go(-1)
    },
    handleSelectionChange (val) {
      this.multipleSelection = val;
    },
    isDisabled (row, index) {
      if (this.pageType === 3) {
        if (index == 0 || index == this.configTableData.list.length - 1) {
          return 0
        } else {
          return 1
        }
      } else {
        return 1
      }

    },
    handleAdd (type) {
      if (type == 'module') {
        // 模块
        this.configTableData.list.push({})
      } else {
        //  过程
        let data = {
          show_obj_list: [],
          show_cfg: {
            show_type: '',
            search_obj_id: '',
            order_field: '',
            order_type: '',
            align_type: ''
          }
        }
        let index = this.configTableData.list.length - 1
        this.configTableData.list.splice(index, 0, data)
      }
    },
    _getList () {
      return CommonCheckApi.getBusinessConfigDetailAPI({
        params: {
          check_tpl_id: this.requestParam.check_tpl_id
        }
      }).then(res => {
        let data = res.data
        this.pageType = Number(data.business_type) //（2：独立模式，3：流程模式，4数据源流程模式）

        this.configTableData = data

        if ((this.pageType == 3 || this.pageType == 4) && data.list.length == 0) {
          this.configTableData.list = [{}, {}]
        }
      })

    },
    _multipleDelete () {
      console.warn(this.multipleSelection)
      if (this.multipleSelection.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            let ids = []
            this.multipleSelection.forEach(item => {
              ids.push(item.check_item_id)
            })

            ids.forEach(item => {
              let index = -1
              this.configTableData.list.map((v, ind) => {
                if (v.check_item_id === item) index = ind
              })
              this.configTableData.list.splice(index, 1)
            })

            // this._saveBusinessConfig()
          })

      } else {
        this.$message.warning('请先勾选')

      }

    },
    // 删除已绑定检查项
    deleteItem (row, index) {
      // 没有id，则是新增的还未保存的，直接删除
      if (!row.check_item_id) {
        this.configTableData.list.splice(index, 1)
      } else {
        // 有id的，走接口删除
        console.log(row, 'delete item')
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {

            // 获取被删除行的index
            let index = -1
            this.configTableData.list.map((item, ind) => {
              if (item.check_item_id === row.check_item_id) index = ind
            })
            this.configTableData.list.splice(index, 1)
            // this._saveBusinessConfig()
          })
          .catch(() => {

          })
      }

    },
    // 调用保存接口
    _saveBusinessConfig () {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          // 验证通过

          let data = {
            check_tpl_id: this.requestParam.check_tpl_id,
            business_type: this.pageType,
            tpl_config: this.configTableData.list,
          }
          data.tpl_config.forEach((v, idx) => {
            v.sort = idx + 1
            if (v.show_obj_list && v.show_obj_list.length > 0) {
              // let obj = v.show_obj_list.find(k => {
              //   return k.show_obj_name == v.show_obj_name
              // })
              // v.show_obj = obj.show_obj
            } else {
              // v.show_obj = ''
            }

          })

          if (this.pageType == 3 || this.pageType == 4) {
            data.tpl_config.forEach((v, idx) => {
              v.node_no = idx + 1
              v.node_type = idx + 1


              if (idx == 0) {
                v.node_name = '开始'
              } else if (idx == data.tpl_config.length - 1) {
                v.node_name = '结束'
                v.node_type = 999
              } else {
                v.node_name = `过程${idx}`
              }
            })
          }
          console.warn(data, 'data')
          CommonCheckApi.saveBusinessConfigAPI({
            data: data
          }).then(res => {
            if (res.code === 0) {
              this.$message.success('操作成功')
              // this._getList()
              this.$router.push({
                path: '/checkBusinessConfig'
              })
              // this._getList()
            }
          })
        } else {
          this.$message.warning('请检查表单内容')
        }
      })

    },


    _changeLinkFormList (row, rowIndex) {
      // 遍历列表，判断是否已经选择了数据源表单
      let flag = false
      // 通过check_item_id获取到对应表单对象
      let checkItem = this.checkItemMap.get(row.check_item_id) || {}
      for (let index in this.configTableData.list) {
        let item = this.configTableData.list[index]
        if (item.item_type === '3' && index != rowIndex && checkItem.item_type === '3') {
          flag = true
          break
        }
      }
      if (flag) {
        this.$message.warning('只能选择一个数据源表单')
        this.configTableData.list[rowIndex].check_item_id = ''
      } else {
        this.configTableData.list[rowIndex].item_type = checkItem.item_type
      }
      this.configTableData.list[rowIndex].show_obj_list = checkItem.show_obj_list || []
      this.configTableData.list[rowIndex].show_cfg = checkItem.show_cfg || {}
      this.$set(this.configTableData.list[rowIndex], 'show_obj_name', '')
      console.log(this.configTableData.list[rowIndex], 'change link')
    },
    _getLinkFormList () {
      // 只有是数据源流程模式时，能配置数据源表单，其它情况都不能
      let itemType = ''
      if (this.pageType == '4') {
        itemType = '2,3'
      } else {
        itemType = '2'
      }
      CommonCheckApi.getLinkFormListAPI({
        params: {
          search_word: '',
          item_type: itemType
        }
      }).then(res => {
        this.link_form_list = res.data.list
        this.link_form_list.map((item) => {
          this.checkItemMap.set(item._id, item)
        })
      })
    },

    getShowObjList (val, index) {
      CommonCheckApi.getShowObjListAPI({ params: { check_item_id: val } }).then(res => {
        // this.show_obj_list = res.data.list
        let list = res.data.list || []
        list.map((item) => {
          item.is_show = false
        })
        this.$set(this.configTableData.list[index], 'show_obj_list', list)
      })

    }
  },
  async mounted () {
    this.requestParam.check_tpl_id = this.$route.query.id
    await this._getList()
    this._getLinkFormList()
  }
}
</script>
<style scoped lang='scss'>
.CheckBusinessConfigDetailClass {
  padding: 20px;
  .el-form-item {
    margin-bottom: 0;
  }

  .el-table {
    margin-top: 20px;
  }

  .btn-groups {
    text-align: center;
    margin-top: 20px;
  }
  .flow-config-container {
    display: flex;
    margin-bottom: 20px;
    .operator {
      width: 100px;
      margin: 0 10px;
    }
    .value {
      width: 100px;
      margin-right: 10px;
    }
    .operation-type {
      margin-right: 10px;
    }
  }
}
</style>
